const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const koajwt = require('koa-jwt');
const login = require('./routes/login')
const admin = require('./routes/admin')
const apply = require('./routes/apply')
const fitment = require('./routes/fitment')
const news = require('./routes/news')

const app = new Koa();

app.use(async (ctx, next)=> {
    // 解决跨域和域检
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200; 
    } else {
        await next();
    }
});

app.use((ctx, next) => {
    return next().catch((err) => {
        if(err.status === 401){
            // ctx.status = 401;
            ctx.body = {
                code: 401,
                msg: 'token已过期请重新登录！'
            };
        }else{
            throw err;
        }
    })
})

app.use(koajwt({secret:'my_token'}).unless({
    path:[
        /^\/login/,
        // /^\/news_list/,
        // /^\/api\/news_list/,
        // /^((?!\/api).)*$/   // 设置除了私有接口外的其它资源，可以不需要认证访问
    ]
}))

app.use(bodyParser());


app.use(login.routes());
app.use(admin.routes());
app.use(apply.routes());
app.use(fitment.routes());
app.use(news.routes());


app.listen(3010);